<template>
  <div class="chart-container">
    <h2>矿物质含量表</h2>
    <div id="mineralContentChart" class="chart"></div>
    
    <div class="chart-controls">
      <span>选择年份：</span>
      <el-radio-group v-model="selectedYear" @change="updateChart">
        <el-radio-button label="2023">2023</el-radio-button>
        <el-radio-button label="2024">2024</el-radio-button>
      </el-radio-group>
      
      <span style="margin-left: 20px;">选择产地：</span>
      <el-radio-group v-model="selectedRegion" @change="updateChart">
        <el-radio-button label="产地A">产地A</el-radio-button>
        <el-radio-button label="产地B">产地B</el-radio-button>
      </el-radio-group>
      
      <el-button type="primary" style="margin-left: 20px;" @click="showAllData">显示所有数据</el-button>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { onMounted, onUnmounted, ref, computed, watch } from 'vue'

export default {
  name: 'MineralContentChart',
  props: {
    year: {
      type: String,
      default: '2023'
    },
    region: {
      type: String,
      default: '产地A'
    }
  },
  setup(props) {
    const selectedYear = ref(props.year)
    const selectedRegion = ref(props.region)
    let chartInstance = null
    
    // 基础矿物质含量数据（两年两个产地）
    const baseMineralContentData = {
      '2023': {
        '产地A': [
          [0, 0, 45],  // 钙
          [0, 1, 38],  // 铁
          [0, 2, 22],  // 锌
          [0, 3, 15],  // 镁
          [0, 4, 8]    // 钾
        ],
        '产地B': [
          [0, 0, 42],  // 钙
          [0, 1, 40],  // 铁
          [0, 2, 25],  // 锌
          [0, 3, 18],  // 镁
          [0, 4, 10]   // 钾
        ]
      },
      '2024': {
        '产地A': [
          [0, 0, 48],  // 钙
          [0, 1, 42],  // 铁
          [0, 2, 26],  // 锌
          [0, 3, 17],  // 镁
          [0, 4, 9]    // 钾
        ],
        '产地B': [
          [0, 0, 44],  // 钙
          [0, 1, 43],  // 铁
          [0, 2, 28],  // 锌
          [0, 3, 20],  // 镁
          [0, 4, 12]   // 钾
        ]
      }
    }
    
    // 区域调整系数
    const regionAdjustment = {
      '全国': 1.0,
      '华北': 1.08,
      '华东': 0.95,
      '华南': 0.92,
      '西北': 1.12,
      '东北': 1.05,
      '西南': 0.98,
      '产地A': 1.0,
      '产地B': 1.0
    }
    
    // 计算最终显示的数据
    const mineralContentData = computed(() => {
      const adjustedData = { ...baseMineralContentData }
      const adjustmentFactor = regionAdjustment[props.region] || 1.0
      
      // 对每个年份和产地的数据应用区域调整系数
      Object.keys(adjustedData).forEach(year => {
        Object.keys(adjustedData[year]).forEach(region => {
          adjustedData[year][region] = adjustedData[year][region].map(item => {
            // 复制原数组
            const newItem = [...item]
            // 调整值（第三列）
            newItem[2] = Number((newItem[2] * adjustmentFactor).toFixed(1))
            return newItem
          })
        })
      })
      
      return adjustedData
    })
    
    // 合并所有数据用于对比显示
    const getAllData = () => {
      const allData = []
      let row = 0
      
      Object.keys(mineralContentData.value).forEach(year => {
        Object.keys(mineralContentData.value[year]).forEach(region => {
          mineralContentData.value[year][region].forEach(item => {
            // 创建新的数组，修改行索引以区分不同的年份和产地
            const newItem = [...item]
            newItem[0] = row
            allData.push(newItem)
          })
          row++
        })
      })
      
      return allData
    }
    
    const initChart = () => {
      const chartDom = document.getElementById('mineralContentChart')
      chartInstance = echarts.init(chartDom)
      
      updateChart()
    }
    
    const updateChart = () => {
      if (!chartInstance) return
      
      const currentYear = selectedYear.value
      const currentRegion = selectedRegion.value
      
      // 确保数据存在的安全检查
      const chartData = mineralContentData.value && mineralContentData.value[currentYear] 
        ? (mineralContentData.value[currentYear][currentRegion] || 
           mineralContentData.value[currentYear]['产地A'] || 
           mineralContentData.value[currentYear]['产地B'] || [])
        : []
      
      const option = {
        title: {
          text: `矿物质含量热力图 - ${currentYear}年 ${currentRegion}${props.region !== currentRegion ? ` (${props.region})` : ''}`,
          left: 'center',
          textStyle: {
            color: '#145A32',
            fontWeight: 'bold'
          }
        },
        tooltip: {
          position: 'top'
        },
        grid: {
          height: '50%',
          top: '20%'
        },
        xAxis: {
          type: 'category',
          data: ['钙(%)', '铁(mg/kg)', '锌(mg/kg)', '镁(%)', '钾(%)'],
          splitArea: {
            show: true
          }
        },
        yAxis: {
          type: 'category',
          data: [currentRegion],
          splitArea: {
            show: true
          }
        },
        visualMap: {
          min: 0,
          max: 50,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '10%',
          color: ['#145A32', '#D4EFDF', '#FFFFFF']
        },
        series: [{
          name: '矿物质含量',
          type: 'heatmap',
          data: chartData,
          label: {
            show: true
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      
      chartInstance.setOption(option)
    }
    
    const showAllData = () => {
      if (!chartInstance) return
      
      const option = {
        title: {
          text: `矿物质含量历年各产地对比热力图${props.region !== '全国' ? ` (${props.region})` : ''}`
        },
        yAxis: {
          data: ['2023年产地A', '2023年产地B', '2024年产地A', '2024年产地B']
        },
        series: [{
          data: getAllData()
        }]
      }
      
      chartInstance.setOption(option)
    }
    
    const resizeChart = () => {
      if (chartInstance) {
        chartInstance.resize()
      }
    }
    
    // 监听props变化
    watch(() => [props.year, props.region], ([newYear, newRegion]) => {
      selectedYear.value = newYear
      // 如果当前选中的产地是'产地A'或'产地B'，则保持不变；否则更新为默认值
      if (!['产地A', '产地B'].includes(selectedRegion.value)) {
        selectedRegion.value = '产地A'
      }
      updateChart()
    }, { immediate: false })
    
    onMounted(() => {
      initChart()
      window.addEventListener('resize', resizeChart)
    })
    
    onUnmounted(() => {
      window.removeEventListener('resize', resizeChart)
      if (chartInstance) {
        chartInstance.dispose()
      }
    })
    
    return {
      selectedYear,
      selectedRegion,
      updateChart,
      showAllData
    }
  }
}
</script>

<style scoped>
.chart-container {
  background: var(--color-card-bg);
  border-radius: 8px;
  padding: 20px;
  box-shadow: var(--color-shadow);
  margin-bottom: 30px;
}

.chart {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}

.chart-controls {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

h2 {
  color: var(--color-primary);
  font-size: 1.8rem;
  margin-bottom: 15px;
  text-align: center;
}
</style>